package jiaerc.moreingredients.block;

import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.block.*;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.loot.LootContext;
import net.minecraft.state.IntegerProperty;
import net.minecraft.state.StateContainer.Builder;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;
//引入自己的类
import jiaerc.moreingredients.MoreIngredientsItems;
import net.minecraftforge.common.ForgeHooks;

import java.util.List;
import java.util.Random;

public class GreenPepperCropsBlock extends CropsBlock{
    public GreenPepperCropsBlock(){
        super(Properties.of(Material.PLANT)
                .lightLevel((state) -> 0)
                .noCollission()
                .noOcclusion()
                .randomTicks()
                .instabreak()
                .sound(SoundType.CROP));
    }
    //状态注册方法
    @Override
    protected void createBlockStateDefinition(Builder<Block, BlockState> builder) {
        builder.add(AGE); // 必须明确注册属性
    }

    public static final IntegerProperty AGE = IntegerProperty.create("age",0,10);
    public static final VoxelShape[] SHAPE_BY_AGE = new VoxelShape[]{
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 2.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 4.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 6.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 10.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 12.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 14.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D),
            Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D)};
    //重写getShape方法，让返回的方块形状是我定义的SHAPE_BY_AGE
    @Override
    public VoxelShape getShape(BlockState blockState , IBlockReader blockReader , BlockPos blockPos , ISelectionContext selectionContext){
        return GreenPepperCropsBlock.SHAPE_BY_AGE[blockState.getValue(this.getAgeProperty())];
    }
    //重写获得阶段方法
    @Override
    public IntegerProperty getAgeProperty(){
        return GreenPepperCropsBlock.AGE;
    }
    @Override
    public int getMaxAge(){
        return 10;
    }
    //重写种子获取
    @Override
    protected IItemProvider getBaseSeedId() {
        return MoreIngredientsItems.GREEN_PEPPER_SEEDS.get();
    }
    //重写生长方法，在前8个阶段生长速度比较快，后面的3个阶段生长速度比较慢
    @Override
    public void randomTick(BlockState blockState, ServerWorld serverWorld, BlockPos blockPos, Random random) {
        if (!serverWorld.isAreaLoaded(blockPos, 1)) return;
        if (serverWorld.getRawBrightness(blockPos, 0) >= 9) {
            int currentAge = blockState.getValue(this.getAgeProperty());
            if (currentAge < this.getMaxAge()) {
                // 根据阶段设置生长速度因子
                float growthFactor = (currentAge < 8) ? 1.0F : 0.6F; // 前8阶段正常速度，后3阶段减半
                // 获取基础生长速度（考虑耕地湿润等环境因素）
                float baseSpeed = getGrowthSpeed(this, serverWorld, blockPos);
                // 计算实际生长概率（25是基准值，数值越小生长越快）
                int chance = (int)(25.0F / (baseSpeed * growthFactor)) + 1;
                // 触发Forge生长事件
                if (ForgeHooks.onCropsGrowPre(serverWorld, blockPos, blockState, random.nextInt(chance) == 0)) {
                    // 更新生长阶段
                    serverWorld.setBlock(blockPos, this.withAge(currentAge + 1), 2);
                    ForgeHooks.onCropsGrowPost(serverWorld, blockPos, blockState);
                }
            }
        }
    }

    // 添加辅助方法获取当前阶段状态
    public BlockState withAge(int age) {
        return this.defaultBlockState().setValue(AGE, Math.min(age, this.getMaxAge()));
    }
    // 处理右键收获（剪刀）
    @Override
    public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) {
        int age = state.getValue(getAgeProperty());
        ItemStack heldItem = player.getItemInHand(hand);
        // 检查是否使用剪刀且处于成熟阶段（8-10）
        if (heldItem.getItem() == Items.SHEARS && age >= 8) {
            if (!world.isClientSide) {
                // 掉落收获物（只有成熟的时候才有果实，然后果实的数量随机）种子都是一个
                int fruitCount = age == 10 ? 3+ world.random.nextInt(2) : 0;
                int seedCount = age == 10 ? 1 : 0;
                popResource(world, pos, new ItemStack(MoreIngredientsItems.GREEN_PEPPER.get(), fruitCount));
                popResource(world, pos, new ItemStack(MoreIngredientsItems.GREEN_PEPPER_SEEDS.get(), 1));
                // 播放收获音效
                world.playSound(null, pos, SoundEvents.CROP_BREAK, SoundCategory.BLOCKS, 1.0F, 1.0F);
                // 重置到第7阶段
                world.setBlock(pos, state.setValue(AGE, 7), 2);
                // 消耗剪刀耐久
                heldItem.hurtAndBreak(1, player, (p) -> p.broadcastBreakEvent(hand));
            }
            return ActionResultType.sidedSuccess(world.isClientSide);
        }
        return super.use(state, world, pos, player, hand, hit);
    }
    // 处理破坏时的掉落物
    @Override
    public void playerWillDestroy(World world, BlockPos pos, BlockState state, PlayerEntity player) {
        super.playerWillDestroy(world, pos, state, player);
        int age = getAge(state);
        // 只有成熟阶段才掉落额外物品，种子只有一个
        if (!world.isClientSide && age >= 8 && !player.isCreative()) {
            int fruitCount = age == 10 ? 3+ world.random.nextInt(2): 0;
            popResource(world, pos, new ItemStack(MoreIngredientsItems.GREEN_PEPPER.get(), fruitCount));
            popResource(world, pos, new ItemStack(MoreIngredientsItems.GREEN_PEPPER_SEEDS.get(), 1));
        }
    }

    @Override
    protected boolean mayPlaceOn(BlockState state, IBlockReader world, BlockPos pos) {
        return state.is(Blocks.FARMLAND);
    }
}
